import type { Router, RouteRecordRaw } from "vue-router"

import { usePermissionStoreWithOut } from "/@/store/modules/permission"
import { getRouteAllPath } from "/@/router/helper/routeHelper"
import { PageEnum } from "/@/enums/pageEnum"
import { useUserStoreWithOut } from "/@/store/modules/user"
import { PAGE_NOT_FOUND_ROUTE } from "/@/router/routes/basic"

import { RootRoute } from "/@/router/routes"

import { useGlobSetting } from "/@/hooks/setting"
import { useIam } from "/@/hooks/web/useIam"
import { getPathFromUrl } from "/@/utils"

const glob = useGlobSetting()
const LOGIN_PATH = PageEnum.BASE_LOGIN
const ROOT_PATH = RootRoute.path
const whitePathList: PageEnum[] = [
  LOGIN_PATH, PageEnum.THIRD_LOGIN_PAGE_PATH, PageEnum.INVITE_USER_JOIN_TENANT,
  PageEnum.OAUTH_CALLBACK
]

export async function createPermissionGuard(router: Router) {
  const userStore = useUserStoreWithOut()
  const permissionStore = usePermissionStoreWithOut()
  router.beforeEach(async (to, from, next) => {
    console.log("from:", from.path, "to: ", to.path)

    if (
      from.path === ROOT_PATH &&
      to.path === PageEnum.BASE_HOME &&
      userStore.getUserInfo.homePath &&
      userStore.getUserInfo.homePath !== PageEnum.BASE_HOME
    ) {
      const homePath = userStore.getUserInfo.homePath
      next(!homePath || homePath === "/" ? PageEnum.BASE_HOME : homePath)
      return
    }

    // Whitelist can be directly entered
    if (whitePathList.filter((e) => to.path.startsWith(e))?.length > 0) {
      next()
      return
    }

    if (to.meta.ignoreAuth) {
      next()
      return
    }

    // Jump to the 404 page after processing the login
    if (from.path === LOGIN_PATH && to.name === PAGE_NOT_FOUND_ROUTE.name && to.fullPath !== (userStore.getUserInfo.homePath || PageEnum.BASE_HOME)) {
      next(userStore.getUserInfo.homePath || PageEnum.BASE_HOME)
      return
    }

    if (permissionStore.getIsDynamicAddedRoute) {
      // 如果是通过sso跳转到iam系统进行登录, 登录成功后会携带redirect(用户自定义)和code, 则直接跳转到redirect即可
      if (to.query.redirect) {
        next({ path: getPathFromUrl(to.query.redirect),  replace: true })
        return
      }
      next()
      return
    }
    const routes = await permissionStore.buildRoutesAction()
    routes.forEach((route) => {
      router.addRoute(route as unknown as RouteRecordRaw)
    })

    router.addRoute(PAGE_NOT_FOUND_ROUTE as unknown as RouteRecordRaw)

    permissionStore.setDynamicAddedRoute(true)

    if (to.name === PAGE_NOT_FOUND_ROUTE.name) {
      // 动态添加路由后，此处应当重定向到fullPath，否则会加载404页面内容
      next({ path: to.fullPath, replace: true, query: to.query })
    } else {
      const redirectPath = (from.query.redirect || to.path) as string
      const redirect = decodeURIComponent(redirectPath)
      const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }

      next(nextData)
    }
  })
}
